package com.ygxsk.carhome.ui.auth;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.flyco.roundview.RoundTextView;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.Toaster;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.trello.rxlifecycle4.android.ActivityEvent;
import com.yanzhenjie.permission.runtime.Permission;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.alertview.AlertView;
import com.ygxsk.carhome.alertview.OnItemClickListener;
import com.ygxsk.carhome.configeng.GifSizeFilter;
import com.ygxsk.carhome.configeng.Glide4Engine;
import com.ygxsk.carhome.constant.ConstantApi;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.constant.ExtraKey;
import com.ygxsk.carhome.constant.ExtraValue;
import com.ygxsk.carhome.event.EventAuthDetail;
import com.ygxsk.carhome.event.EventAuthMain;
import com.ygxsk.carhome.listener.AuthorityCallbackListener;
import com.ygxsk.carhome.listener.DoSomeThingListener;
import com.ygxsk.carhome.listener.ErrorParentExtraSingle;
import com.ygxsk.carhome.listener.GainDataCallBackListener;
import com.ygxsk.carhome.listener.RxBus;
import com.ygxsk.carhome.response.AuthSystemEntity;
import com.ygxsk.carhome.response.CarAttestation;
import com.ygxsk.carhome.response.EvaluateWadeInfo;
import com.ygxsk.carhome.retrofit.AddLogUpLoadInfo;
import com.ygxsk.carhome.retrofit.ApiException;
import com.ygxsk.carhome.retrofit.ApiRequestSubListener;
import com.ygxsk.carhome.retrofit.ApiService;
import com.ygxsk.carhome.retrofit.ErrorConsumer;
import com.ygxsk.carhome.retrofit.NetworkManager;
import com.ygxsk.carhome.retrofit.ResponseTransformer;
import com.ygxsk.carhome.rxbus.RxBusCalendarTime;
import com.ygxsk.carhome.rxbus.RxBusCarWade;
import com.ygxsk.carhome.sys.PermissionNameConvert;
import com.ygxsk.carhome.ui.ErrorActivity;
import com.ygxsk.carhome.ui.evaluate.CalendarViewCustomPopup;
import com.ygxsk.carhome.ui.evaluate.EvaluateWadePopu;
import com.ygxsk.carhome.utils.CommUtils;
import com.ygxsk.integrated.retrofit.Parameterkey;
import com.zhongjh.albumcamerarecorder.album.filter.BaseFilter;
import com.zhongjh.albumcamerarecorder.preview.BasePreviewActivity;
import com.zhongjh.albumcamerarecorder.settings.AlbumSetting;
import com.zhongjh.albumcamerarecorder.settings.CameraSetting;
import com.zhongjh.albumcamerarecorder.settings.GlobalSetting;
import com.zhongjh.albumcamerarecorder.settings.MultiMediaSetting;
import com.zhongjh.common.entity.LocalFile;
import com.zhongjh.common.entity.MultiMedia;
import com.zhongjh.common.entity.SaveStrategy;
import com.zhongjh.common.enums.MimeType;
import com.zhongjh.progresslibrary.entity.MultiMediaView;
import com.zhongjh.progresslibrary.listener.MaskProgressLayoutListener;
import com.zhongjh.progresslibrary.widget.MaskProgressLayout;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

/*
 * @Author:itchenqi175@163.com
 * @Time:2023-07-24  08:46
 * @Description:添加车辆的认证，是上传认证结果，
 */
public class AuthAddSubmitActivity extends ErrorActivity implements EasyPermissions.PermissionCallbacks, ErrorParentExtraSingle {

    @BindView(R.id.layoutbuttonauthaddsubmit)
    RoundTextView layoutButtonAuthAddSubmit;

    //认证体系的外侧包裹
    @BindView(R.id.layoutauthauthwherename)
    LinearLayout layoutAuthAuthWhereName;

    //认证体系的文字描述
    @BindView(R.id.textviewauthsystemwherename)
    TextView textViewAuthSystemWhereName;

    //认证时间选择
    @BindView(R.id.layoutauthtime)
    LinearLayout layoutAuthTime;

    //认证时间的真实填充
    @BindView(R.id.textviewauthtime)
    TextView textViewAuthTime;

    //选择图片上传的信息
    @BindView(R.id.mplimagelistinauthcheck)
    MaskProgressLayout mplimageListInAuthCheck;

//    //车辆品牌的外侧包裹
//    @BindView(R.id.layoutauthcarbrand)
//    LinearLayout layoutAuthCarBrand;

//    //车辆品牌填充
//    @BindView(R.id.textviewauthcarbrand)
//    TextView textViewAuthCarBrand;

    //选择认证体系的 底部弹窗；
    private BasePopupView basePopupView_formWhere;
    //车辆认证时间的选择弹窗；
    private BasePopupView basePopupView_authSystem_time;

    //车辆认证体系的那个id,上传用；
    private String shopAttestationId_upLoad;
    //认证体系的名称
    private String attestationName_upLoad;
    //添加 车辆认证主键ID
    private String carAttestationId_upLoad;
    //添加车辆认证时间
    private String createTime_upLoad;

    //做图片上传的操作
    private static final int PRC_PHOTO_PICKER = 1;
    //图片的选择等
    protected static final int REQUEST_CODE_CHOOSE = 2361;

    //一个临时的客户来源的列表；
    private ArrayList<AuthSystemEntity> mDataResources_authSystem = new ArrayList<>();

    //车辆认证通用的弹窗
    private ArrayList<EvaluateWadeInfo> mDataResources_wadeAuthList = new ArrayList<>();

    //该页面的编辑的图片的hashMap
    private ArrayList<HashMap<String, Object>> fileSingleUpLoadFiles_upLoad_hashMap = new ArrayList<>();

    private int alreadyImageCount;
    private int alreadyVideoCount;
    private int alreadyAudioCount;

    //添加相机的设置
    private GlobalSetting mGlobalSetting;
    //携带详情过来的 该认证的id过来；
    private CarAttestation extra_carattestation;


    @OnClick({R.id.layoutbuttonauthaddsubmit, R.id.layoutauthauthwherename, R.id.layoutauthtime})//
    public void onViewClickInAuthAdd(View v) {

        switch (v.getId()) {

            //执行保存提交
            case R.id.layoutbuttonauthaddsubmit: {

                //姓名必填
                if (TextUtils.isEmpty(shopAttestationId_upLoad) || TextUtils.isEmpty(attestationName_upLoad)) {
                    CommUtils.checkDialog(mAlertView);
                    mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.select_evaluate_authsystem), true);
                    mAlertView.show();
                    return;
                }

                //手机号校验
                if (TextUtils.isEmpty(createTime_upLoad)) {
                    CommUtils.checkDialog(mAlertView);
                    mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.please_choose_auth_time), true);
                    mAlertView.show();
                    return;
                }

                //车辆认证的图片也是必填吧，毕竟是一个认证结果
                if (fileSingleUpLoadFiles_upLoad_hashMap != null && fileSingleUpLoadFiles_upLoad_hashMap.isEmpty()) {
                    CommUtils.checkDialog(mAlertView);
                    mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.please_choose_auth_images), true);
                    mAlertView.show();
                    return;
                }

                CommUtils.checkDialog(mAlertView);
                mAlertView = new AlertView(StringUtils.getString(R.string.clearaddorsubmitsuretitletips), //提示
                        StringUtils.getString(R.string.clearaddorsubmitsuremessage),//提示内容
                        StringUtils.getString(R.string.clearcachecancel), //取消
                        new String[]{StringUtils.getString(R.string.clearaddorsubmitsure)},//确定
                        null, mActivityInstance, AlertView.Style.Alert, new OnItemClickListener() {//
                    @Override
                    public void onItemClick(Object o, int position) {

                        if (position != AlertView.CANCELPOSITION) {

                            method_gainAddSubmitInfo_upLoad();

                        }
                    }
                });

                mAlertView.setCancelable(true);
                mAlertView.show();

                break;
            }


            case R.id.layoutauthauthwherename: {//打开认证体系的弹窗；

                EvaluateWadePopu evaluateWadePopu = new EvaluateWadePopu(AuthAddSubmitActivity.this,//
                        ExtraValue.MODIFY_EVALUATE_AUTH_SYSTEM_SELECT,//
                        mDataResources_wadeAuthList);

                evaluateWadePopu.setTitleName(getResources().getString(R.string.please_choose_auth_system));

                basePopupView_formWhere = new XPopup.Builder(AuthAddSubmitActivity.this)
                        .hasShadowBg(true)
                        .isViewMode(true)
                        .asCustom(evaluateWadePopu)//
                        .show();

                break;
            }

            case R.id.layoutauthtime: {//添加点击 获取时间的 事件；

                CalendarViewCustomPopup calendarViewCustomPopup = new CalendarViewCustomPopup(ExtraValue.RXBUS_EVALUATE_CAR_AUTH_SYSTEM_TO_ADDSUBMIT, AuthAddSubmitActivity.this);

                //直接弹窗选择时间的
                basePopupView_authSystem_time = new XPopup.Builder(AuthAddSubmitActivity.this)
                        .hasShadowBg(true)
                        .moveUpToKeyboard(false)
                        .isViewMode(true)
                        .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                        .isThreeDrag(false)//
                        .asCustom(calendarViewCustomPopup)//
                        .show();

                break;
            }

            default:
                break;
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mActivityInstance = this;

        processExtraData();

        if (mDataResources_authSystem == null) {
            mDataResources_authSystem = new ArrayList<>();
        }

        if (mDataResources_wadeAuthList == null) {
            mDataResources_wadeAuthList = new ArrayList<>();
        }

        initViews();

        //预加载列表
        gainDatas();

        mCompositeDisposable.add(RxBus.getInstance()
                .toObserverable(RxBusCarWade.class)//
                .subscribeOn(AndroidSchedulers.mainThread())//
                .observeOn(AndroidSchedulers.mainThread())//
                .subscribe(new Consumer<RxBusCarWade>() {

                    @Override
                    public void accept(RxBusCarWade rxBusCarWade) throws Throwable {

                        if (rxBusCarWade != null) {

                            if (rxBusCarWade.getActionFlag() == ExtraValue.MODIFY_EVALUATE_AUTH_SYSTEM_SELECT) {//【车辆认证体系的店铺id】；

                                //车辆涉水的id
                                shopAttestationId_upLoad = rxBusCarWade.getEvaluateWadeInfo().getDictCode();
                                attestationName_upLoad = rxBusCarWade.getEvaluateWadeInfo().getDictLabel();

                                //修改文本
                                if (textViewAuthSystemWhereName != null) {
                                    textViewAuthSystemWhereName.setText(rxBusCarWade.getEvaluateWadeInfo().getDictLabel());
                                }

                            }
                        }
                    }
                }));

        //监听认证日期
        mCompositeDisposable.add(RxBus.getInstance()
                .toObserverable(RxBusCalendarTime.class)//
                .subscribeOn(AndroidSchedulers.mainThread())//
                .observeOn(AndroidSchedulers.mainThread())//
                .subscribe(new Consumer<RxBusCalendarTime>() {

                    @Override
                    public void accept(RxBusCalendarTime rxBusCalendarTime) throws Throwable {

                        if (rxBusCalendarTime != null) {

                            if (rxBusCalendarTime.getActionFlag() == ExtraValue.RXBUS_EVALUATE_CAR_AUTH_SYSTEM_TO_ADDSUBMIT) {//【车辆认证】时间；

                                //变动 认证时间 做上传用；
                                createTime_upLoad = rxBusCalendarTime.getManufactureDate();

                                //修改文本
                                if (textViewAuthTime != null) {
                                    textViewAuthTime.setText(rxBusCalendarTime.getManufactureDate());
                                }

                            }
                        }
                    }
                }));

        //图片配置初始化
        initConfig();

    }

    private void initConfig() {

        // 拍摄有关设置
        CameraSetting cameraSetting = new CameraSetting();
        // 支持的类型：图片，视频
        cameraSetting.mimeTypeSet(MimeType.ofImage());
        // 相册
        AlbumSetting albumSetting = new AlbumSetting(true)
                // 支持的类型：图片，视频
                .mimeTypeSet(MimeType.ofImage())
                // 仅仅显示一个多媒体类型
                .showSingleMediaType(true)
                // 是否显示多选图片的数字
                .countable(true)
                // 自定义过滤器
                .addFilter(new GifSizeFilter(320, 320, 5 * BaseFilter.K * BaseFilter.K))
                // 九宫格大小
                .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                // 图片缩放比例
                .thumbnailScale(0.85f)
                .setOnSelectedListener(localFiles -> {
                    // 每次选择的事件
//                    LogUtils.d("itchen---onSelected", "onSelected: localFiles.size()=" + localFiles.size());
                })
                // 开启原图
                .originalEnable(true)
                // 最大原图size,仅当originalEnable为true的时候才有效
                .maxOriginalSize(1)
                .setOnCheckedListener(isChecked -> {
                    // 是否勾选了原图
//                    LogUtils.d("itchen----isChecked", "onCheck: isChecked=" + isChecked);
                });
        // 录音机
//        RecorderSetting recorderSetting = new RecorderSetting();
        // 全局
        mGlobalSetting = MultiMediaSetting.from(AuthAddSubmitActivity.this)
                .choose(MimeType.ofImage())
                .albumSetting(albumSetting)
                .cameraSetting(cameraSetting)
                .isImageEdit(false)
//                .recorderSetting(recorderSetting)
                // 设置路径和7.0保护路径等等
                .allStrategy(new SaveStrategy(true, "com.ygxsk.carhome.fileprovider", "AA/test"))
                // 如果设置这个，有关图片的优先权比allStrategy高
                .pictureStrategy(new SaveStrategy(true, "com.ygxsk.carhome.fileprovider", "AA/picture"))
                // 如果设置这个，有关音频的优先权比allStrategy高
                //.audioStrategy(new SaveStrategy(true, "com.ygxsk.integrated.fileprovider", "AA/audio"))
                // 如果设置这个，有关视频的优先权比allStrategy高
                .videoStrategy(new SaveStrategy(true, "com.ygxsk.carhome.fileprovider", "AA/video"))
                //  .imageEngine(new GlideEngine())  // for glide-V3     // for glide-V4
                .imageEngine(new Glide4Engine());

    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();

        ImmersionBar.with(this)//
                .titleBar(R.id.toolbarygxskout)
                .fitsSystemWindows(true)//解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                //.statusBarColor(R.color.colorPrimary)//
                //.navigationBarColor(R.color.colorPrimary)//
                //.keyboardEnable(true)
                .init();
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_auth_add_submit;
    }

    @Override
    protected void initToolBar(ToolbarHelper toolbarHelper) {

        toolbarHelper.setTitle(getString(R.string.add_submit_auth_manage));
        toolbarHelper.setVersionName(true, AppUtils.getAppVersionName());
        toolbarHelper.setLayoutClose(false, "", null);

        toolbarHelper.setLayoutLeft(true, R.drawable.backicon, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //搜索客户信息，优先关闭软键盘
                KeyboardUtils.hideSoftInput(mActivityInstance);
                methodBack();
            }
        });

        toolbarHelper.setLayoutRight(false, 0, "", null);

    }

    @Override
    protected void onClickNodata(View v) {

        //

    }

    @Override
    protected void initViews() {


        //图片上传控件的监听器
        //处理添加图片的监听
        mplimageListInAuthCheck.setMaskProgressLayoutListener(new MaskProgressLayoutListener() {
            @Override
            public void onItemAdd(@NonNull View view, @NonNull MultiMediaView multiMediaView,
                                  int _alreadyImageCount,//
                                  int _alreadyVideoCount, //
                                  int _alreadyAudioCount) {//
                //alreadyImageCount, alreadyVideoCount, alreadyAudioCount

                alreadyImageCount = _alreadyImageCount;
                alreadyVideoCount = _alreadyVideoCount;
                alreadyAudioCount = _alreadyAudioCount;

                //判断版本号
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {

                    choicePhotoWrapper();

                } else {

                    choicePhotoWrapperXXPermissions();

                }

            }

            @Override
            public void onItemClick(@NonNull View view, @NonNull MultiMediaView multiMediaView) {

                try {
                    //do
                    if (multiMediaView.isImageOrGif() || multiMediaView.isVideo()) {//

                        if (mplimageListInAuthCheck != null) {

                            if (mGlobalSetting != null) {

                                mGlobalSetting.openPreviewData(AuthAddSubmitActivity.this, REQUEST_CODE_CHOOSE,
                                        mplimageListInAuthCheck.getImagesAndVideos(),//
                                        mplimageListInAuthCheck.getImagesAndVideos().//
                                                indexOf(multiMediaView));//
                            } else {
                                ToastUtils.showShort(StringUtils.getString(R.string.globalsettingnull));
                            }
                        }

                    }

                } catch (Exception e) {
                    //catch
                    e.printStackTrace();
                }

            }

            @Override
            public void onItemStartUploading(@NonNull MultiMediaView multiMediaView) {

            }

            @Override
            public void onItemClose(@NonNull View view, @NonNull MultiMediaView multiMediaView) {

                //对图片的编辑；
                try {
                    //do
                    if (multiMediaView != null) {

                        //是否要区分：是【添加图片】还是【从详情里取到的图片】
                        String filePath = multiMediaView.getPath();
//                        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "---filePath-->" + filePath);
                        //itchen-->---filePath-->/storage/emulated/0/middlelow/IMAGE_20230512_173801068.jpg
                        String getCurrentFileShortName = CommUtils.valueStringSplit(filePath);

                        if (fileSingleUpLoadFiles_upLoad_hashMap != null && !fileSingleUpLoadFiles_upLoad_hashMap.isEmpty()) {

                            //遍历循环装载HashMap的list
                            Iterator<HashMap<String, Object>> iterator = fileSingleUpLoadFiles_upLoad_hashMap.iterator();

                            if (iterator != null) {

                                while (iterator.hasNext()) {

                                    HashMap<String, Object> hashMapItem = iterator.next();

                                    if (hashMapItem != null) {

                                        String file_short_name_local = (String) hashMapItem.get(Parameterkey.file_name);

                                        if (!TextUtils.isEmpty(getCurrentFileShortName) && !TextUtils.isEmpty(file_short_name_local)) {
                                            if (TextUtils.equals(getCurrentFileShortName, file_short_name_local)) {
                                                fileSingleUpLoadFiles_upLoad_hashMap.remove(hashMapItem);
                                                LogUtils.json(ConstantSign.LOGCAT_NOMAL + "即将删除--新增的-本地数据-hashMapItem-->", hashMapItem);
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                        }

                    }

                } catch (Exception e) {
                    //catch
                    e.printStackTrace();
                }

            }

            @Override
            public void onItemAudioStartDownload(@NonNull View view, @NonNull String s) {

            }

            @Override
            public boolean onItemVideoStartDownload(@NonNull View view, @NonNull MultiMediaView multiMediaView) {
                return false;
            }

            @Override
            public void onAddDataSuccess(@NonNull List<MultiMediaView> list) {

            }
        });

    }

    //    private void choicePhotoWrapper(int alreadyImageCount, int alreadyVideoCount, int alreadyAudioCount) {
    @AfterPermissionGranted(PRC_PHOTO_PICKER)
    private void choicePhotoWrapper() {

//        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {

        //判断手机是否是大于 android 13的
        String[] perms = {Manifest.permission.CAMERA, Permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};

        if (EasyPermissions.hasPermissions(this, perms)) {

            openMain(alreadyImageCount, alreadyVideoCount, alreadyAudioCount);

        } else {
            EasyPermissions.requestPermissions(this, StringUtils.getString(R.string.imageselectstr_audio), PRC_PHOTO_PICKER, perms);
        }

//        }

    }

    //使用XXPermissions改造选择相册相机，使用openmain是相机和相册同时间调用
    private void choicePhotoWrapperXXPermissions() {

        if (!XXPermissions.isGranted(mActivityInstance, com.hjq.permissions.Permission.CAMERA)
                || !XXPermissions.isGranted(mActivityInstance, com.hjq.permissions.Permission.READ_MEDIA_IMAGES)) {

            CommUtils.checkMaterialDialog(materialDialog);

            materialDialog = CommUtils.authorityRequest(mActivityInstance, ConstantSign.MATERIALDIALOG_AUTHORITY_CONTENT_CAMERA_STORAGE, new AuthorityCallbackListener() {
                @Override
                public void doSomeThing() {

                    CommUtils.checkMaterialDialog(materialDialog);

                    XXPermissions.with(AuthAddSubmitActivity.this)
                            // 适配分区存储应该这样写
                            //.permission(Permission.Group.STORAGE)
                            // 不适配分区存储应该这样写
                            .permission(com.hjq.permissions.Permission.CAMERA)//
                            .permission(com.hjq.permissions.Permission.READ_MEDIA_IMAGES)//
//                                    .permission(com.hjq.permissions.Permission.READ_MEDIA_VIDEO)//
//                                    .permission(com.hjq.permissions.Permission.READ_MEDIA_AUDIO)//
                            //).permission(com.hjq.permissions.Permission.MANAGE_EXTERNAL_STORAGE
//                                                        .interceptor(new PermissionInterceptor())
                            .request(new OnPermissionCallback() {

                                @Override
                                public void onGranted(@NonNull List<String> permissions, boolean allGranted) {

                                    if (!allGranted) {
                                        // TODO: 2024/1/23 18:50 权限这里要不要给提示？权限没通过

                                        return;
                                    }

                                    Toaster.show(String.format(getString(R.string.demo_obtain_permission_success_hint),
                                            PermissionNameConvert.getPermissionString(AuthAddSubmitActivity.this, permissions)));

                                    openMain(alreadyImageCount, alreadyVideoCount, alreadyAudioCount);

                                }
                            });
                }
            });

        } else {

            openMain(alreadyImageCount, alreadyVideoCount, alreadyAudioCount);

        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode != RESULT_OK) {
            return;
        }

        if (requestCode == REQUEST_CODE_CHOOSE) {

            // 如果是在预览界面点击了确定
            if (data.getBooleanExtra(BasePreviewActivity.EXTRA_RESULT_APPLY, false)) {

                // 获取选择的数据
                ArrayList<MultiMedia> selected = MultiMediaSetting.obtainMultiMediaResult(data);
//                LogUtils.d(ConstantSign.LOGCAT_NOMAL + "--selected--的值内容-->" + selected);

                if (selected == null) {
                    return;
                }

                // 循环判断，如果不存在，则删除
                for (int i = mplimageListInAuthCheck.getImagesAndVideos().size() - 1; i >= 0; i--) {

                    int k = 0;

                    for (MultiMedia multiMedia : selected) {
                        if (!mplimageListInAuthCheck.getImagesAndVideos().get(i).equals(multiMedia)) {
                            k++;
                        }
                    }

                    if (k == selected.size()) {
                        // 所有都不符合，则删除
                        mplimageListInAuthCheck.removePosition(i);
                    }

                }

            } else {
                List<LocalFile> result = MultiMediaSetting.obtainLocalFileResult(data);
                ArrayList<String> listUpLoad = new ArrayList<>();
                for (LocalFile localFile : result) {
                    // 绝对路径,AndroidQ如果存在不属于自己App下面的文件夹则无效
//                    LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult id:" + localFile.getId());
//                    LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 绝对路径:" + localFile.getPath());
                    //---/storage/emulated/0/middlelow/IMAGE_20230404_155336703.jpg
//                    LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 旧图路径:" + localFile.getOldPath());
//                    LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 原图路径:" + localFile.getOriginalPath());
//                    LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult Uri:" + localFile.getUri());
//                    LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 旧图Uri:" + localFile.getOldUri());
//                    LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 原图Uri:" + localFile.getOriginalUri());
//                    LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 文件大小: " + localFile.getSize());
//                    LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 视频音频长度: " + localFile.getDuration());
//                    LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 是否选择了原图: " + localFile.isOriginal());
//                    if (localFile.isImageOrGif()) {
//                        if (localFile.isImage()) {
//                            LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 图片类型");
//                        } else if (localFile.isImage()) {
//                            LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 图片类型");
//                        }
//                    } else if (localFile.isVideo()) {
//                        LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 视频类型");
//                    } else if (localFile.isAudio()) {
//                        LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 音频类型");
//                    }
//                    LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 具体类型:" + localFile.getMimeType())
                    // 某些手机拍摄没有自带宽高，那么我们可以自己获取
//                    if (localFile.getWidth() == 0 && localFile.isVideo()) {
//                        MediaExtraInfo mediaExtraInfo = MediaUtils.getVideoSize(getApplication(), localFile.getPath());
//                        localFile.setWidth(mediaExtraInfo.getWidth());
//                        localFile.setHeight(mediaExtraInfo.getHeight());
//                        localFile.setDuration(mediaExtraInfo.getDuration());
//                    }

//                    LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 宽高: " + localFile.getWidth() + "x" + localFile.getHeight());
                    // method_single_image_addSubmit_upLoad(localFile.getPath());

                    if (!TextUtils.isEmpty(localFile.getPath())) {
                        listUpLoad.add(localFile.getPath());
                    }

                    //直接 存储
                    HashMap<String, Object> hashMapTemp = new HashMap<String, Object>();
                    hashMapTemp.put(Parameterkey.file_name, CommUtils.valueStringSplit(localFile.getPath()));
                    hashMapTemp.put(Parameterkey.file_path_local, localFile.getPath());

                    if (fileSingleUpLoadFiles_upLoad_hashMap != null) {
                        fileSingleUpLoadFiles_upLoad_hashMap.add(hashMapTemp);
                    }

                }

//              LogUtils.d(ConstantSign.LOGCAT_NOMAL, "执行了--addLocalFileStartUpload---addLocalFileStartUpload---addLocalFileStartUpload");
                mplimageListInAuthCheck.addLocalFileStartUpload(result);

                //加载完毕添加
                method_test_upLoadHashMap();

            }
        }


    }

    //执行上传操作
    private void method_gainAddSubmitInfo_upLoad() {

        MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder()//
                .setType(MultipartBody.FORM);//

        //不是做上传，是为了做日志上传用的
        ArrayList<String> addLogList = new ArrayList<>();
        if (fileSingleUpLoadFiles_upLoad_hashMap != null && !fileSingleUpLoadFiles_upLoad_hashMap.isEmpty()) {
            for (HashMap<String, Object> hashMapItem : fileSingleUpLoadFiles_upLoad_hashMap) {

                String imageLocalPath = (String) hashMapItem.get(Parameterkey.file_path_local);

                if (!TextUtils.isEmpty(imageLocalPath)) {

                    File file = new File(imageLocalPath);
                    multipartBodyBuilder.addFormDataPart(Parameterkey.files, file.getName(),//
                            RequestBody.create(file, MediaType.parse(ApiService.MEDIATYPE_IMAGE_JPG)));//

                    addLogList.add(imageLocalPath);
                }
            }
        } else {
            LogUtils.d(ConstantSign.LOGCAT_NOMAL + "itchen---->添加报修的图片地址 fileSingleUpLoadFiles_upLoad_hashMap 是空的");
        }

        //仅仅做参数上传addlog用；
        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.carAttestationId, carAttestationId_upLoad);//车辆认证主键ID
        map.put(Parameterkey.shopAttestationId, shopAttestationId_upLoad);//店铺认证体系ID
        map.put(Parameterkey.attestationName, attestationName_upLoad);//
        map.put(Parameterkey.createTime, createTime_upLoad);//认证日期
        map.put(Parameterkey.files, addLogList);//仅仅做日志上传

        //将来可能用
//        map.put(Parameterkey.brandId, brandId_upLoad);//车辆品牌
//        map.put(Parameterkey.seriesId, seriesId_upLoad);//车系ID
//        map.put(Parameterkey.carName, carName_upLoad);//车型

        //============================================================================================================

        multipartBodyBuilder.addFormDataPart(Parameterkey.carAttestationId, carAttestationId_upLoad);
        multipartBodyBuilder.addFormDataPart(Parameterkey.shopAttestationId, shopAttestationId_upLoad);//姓名
        multipartBodyBuilder.addFormDataPart(Parameterkey.attestationName, attestationName_upLoad);//手机号
        multipartBodyBuilder.addFormDataPart(Parameterkey.createTime, createTime_upLoad);//车辆品牌
        //multipartBodyBuilder.addFormDataPart(Parameterkey.files, files_upLoad);//图片的合集

//        if (addLogList != null && !addLogList.isEmpty()) {
//            for (String path : addLogList) {//图片的路径
//                File file = new File(path);
//                //RequestBody requestBodyImages = RequestBody.create(file,MediaType.parse("multipart/form-data"));
//                //RequestBody requestBodyImages = RequestBody.create(file, MediaType.parse(ApiService.MEDIATYPE_IMAGE_JPG));
//                multipartBodyBuilder.addFormDataPart(Parameterkey.files, file.getName(),//
//                        RequestBody.create(file, MediaType.parse(ApiService.MEDIATYPE_IMAGE_JPG)));//
//            }
//        }

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_ADDATTESTATIONRESULT_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.addAttestationResult_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);//仅仅有提交参数的能力

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .addAttestationResult(multipartBodyBuilder.build())
                .compose(AuthAddSubmitActivity.this.bindUntilEvent(ActivityEvent.DESTROY))
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<String>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                        CommUtils.checkMaterialDialog(materialDialog);
                    }
                })).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {

                        method_create_materialDialog(mActivityInstance, ConstantSign.TIPS_SUBMIT);

                    }
                }).subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String stringValue) throws Throwable {
                        //TipDialog.show(StringUtils.getString(R.string.add_submit_success), WaitDialog.TYPE.SUCCESS);

                        CommUtils.checkMaterialDialog(materialDialog);

                        //刷新 车辆认证 的详情页面
                        EventAuthDetail eventAuthDetail = new EventAuthDetail();
                        eventAuthDetail.setMessage(ExtraValue.EVENTBUS_EVENT_TO_REFRESH_AUTH_DETAIL);
                        EventBus.getDefault().post(eventAuthDetail);

                        //通知主页列表刷新
                        EventAuthMain eventAuthMain = new EventAuthMain();
                        eventAuthMain.setMessage(ExtraValue.EVENTBUS_EVENT_TO_REFRESH_AUTH_MAIN_LIST);
                        EventBus.getDefault().post(eventAuthMain);

                        //该页面关闭，
                        //提示提交成功，然后1秒后关闭界面
                        methodSubmitSuccess(AuthAddSubmitActivity.this, new DoSomeThingListener() {
                            @Override
                            public void doSomeThing() {
                                //关闭该页面
                                methodBack();
                            }
                        });


                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                        //retain
                        CommUtils.checkMaterialDialog(materialDialog);

                    }
                });

    }

    private void method_test_upLoadHashMap() {
        //startTime 为了标识是哪个对象的图片;
        for (HashMap<String, Object> hashMapItem : fileSingleUpLoadFiles_upLoad_hashMap) {
            LogUtils.json(ConstantSign.LOGCAT_NOMAL + "上传图片集合为->", hashMapItem);
        }
    }


    /**
     * 公共的打开多媒体事件
     *
     * @param alreadyImageCount 已经存在的图片
     * @param alreadyVideoCount 已经存在的语音
     * @param alreadyAudioCount 已经存在的视频
     */
    private void openMain(int alreadyImageCount, int alreadyVideoCount, int alreadyAudioCount) {

        // 拍摄有关设置
        CameraSetting cameraSetting = new CameraSetting();
        // 支持的类型：图片，视频
//        cameraSetting.mimeTypeSet(MimeType.ofAll());
        cameraSetting.mimeTypeSet(MimeType.ofImage());

        // 相册
        AlbumSetting albumSetting = new AlbumSetting(false)
                // 支持的类型：图片，视频
                .mimeTypeSet(MimeType.ofImage())
                // 是否显示多选图片的数字
                .countable(true)
                // 自定义过滤器
                .addFilter(new GifSizeFilter(320, 320, 5 * BaseFilter.K * BaseFilter.K))
                // 开启原图
                .originalEnable(true)
                // 最大原图size,仅当originalEnable为true的时候才有效
                .maxOriginalSize(10);

        // 录音机
        //RecorderSetting recorderSetting = new RecorderSetting();

        // 全局
        mGlobalSetting = MultiMediaSetting.from(AuthAddSubmitActivity.this).choose(MimeType.ofImage());
        // 开启相册功能
        mGlobalSetting.albumSetting(albumSetting);

        // 开启拍摄功能
        mGlobalSetting.cameraSetting(cameraSetting);

//        if (mBinding.cbRecorder.isChecked()) {
//            // 开启录音功能
//            mGlobalSetting.recorderSetting(recorderSetting);
//        }

        mGlobalSetting
                // 设置路径和7.0保护路径等等
                .allStrategy(new SaveStrategy(true,//
                        ConstantSign.FILE_PROVIDER, //fileProvider
                        ConstantSign.FOLDER_MIDDLELOW))//
                .isImageEdit(false)
                // for glide-V4
                .imageEngine(new Glide4Engine())
                // 最大5张图片、最大3个视频、最大1个音频
                .maxSelectablePerMediaType(null,
                        ConstantApi.MAX_IMAGE_SELECTABLE,//5个图片，整体设置；
                        ConstantApi.MAX_VIDEO_SELECTABLE,
                        ConstantApi.MAX_AUDIO_SELECTABLE,
                        alreadyImageCount,
                        alreadyVideoCount,
                        alreadyAudioCount)
                .forResult(REQUEST_CODE_CHOOSE);

    }

    @Override
    protected void gainDatas() {

        if (NetworkUtils.isConnected()) {
            getServerDatas();
        } else {
            //
        }

    }

    private void getServerDatas() {

        //主要的获取车辆认证体系
        gainAuthSystemList(null);

    }

    //获取车辆的品牌--大范畴
    @SuppressLint("CheckResult")
    private void gainAuthSystemList(GainDataCallBackListener _gainDataCallBackListener) {

        //
        HashMap<String, Object> map = new HashMap<>();
        //map.put(Parameterkey., yourName);

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_GETATTESTATIONLIST_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.getAttestationList_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .getAttestationList(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
                .compose(AuthAddSubmitActivity.this.bindUntilEvent(ActivityEvent.DESTROY))
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<ArrayList<AuthSystemEntity>>(
                        ConstantApi.IS_ACTIVITY_ITSELF, //
                        AuthAddSubmitActivity.this) {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                    }
                })).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {
                        method_create_materialDialog(mActivityInstance, ConstantSign.TIPS_LOADING);
                    }
                }).subscribe(new Consumer<ArrayList<AuthSystemEntity>>() {
                    @Override
                    public void accept(ArrayList<AuthSystemEntity> authSystemEntities) throws Throwable {

                        if (mDataResources_authSystem != null && !mDataResources_authSystem.isEmpty()) {
                            mDataResources_authSystem.clear();
                        }

                        if (authSystemEntities != null && !authSystemEntities.isEmpty()) {

                            if (mDataResources_authSystem != null) {
                                mDataResources_authSystem.addAll(authSystemEntities);
                            }

                            //做类型转换
                            if (mDataResources_authSystem != null && !mDataResources_authSystem.isEmpty()) {

                                for (AuthSystemEntity authSystemEntity : mDataResources_authSystem) {

                                    EvaluateWadeInfo evaluateWadeInfo = new EvaluateWadeInfo();
                                    //店铺认证体系的id;
                                    evaluateWadeInfo.setDictCode(authSystemEntity.getShopAttestationId());
                                    evaluateWadeInfo.setDictLabel(authSystemEntity.getAttestationName());

                                    if (mDataResources_wadeAuthList != null) {
                                        mDataResources_wadeAuthList.add(evaluateWadeInfo);
                                    }

                                }

                            }

                        }

                        CommUtils.checkMaterialDialog(materialDialog);

                        //立即获取车系？没有必要
                        if (_gainDataCallBackListener != null) {
                            _gainDataCallBackListener.doSomeThing();
                        }

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {
                        CommUtils.checkMaterialDialog(materialDialog);
                    }
                });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (basePopupView_formWhere != null) {
            basePopupView_formWhere.onDestroy();
            basePopupView_formWhere = null;
        }


        if (basePopupView_authSystem_time != null) {
            basePopupView_authSystem_time.onDestroy();
            basePopupView_authSystem_time = null;
        }

    }

    @Override
    protected void methodBack() {
        ActivityUtils.finishActivity(this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {

        if (requestCode == PRC_PHOTO_PICKER) {
            Toast.makeText(this, StringUtils.getString(R.string.imageselectdenied), Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    public void processExtraData() {

        Bundle extras_bundle = this.getIntent().getExtras();

        if (extras_bundle != null) {

            //flag_jumpfrom_where_type = extras_bundle.getString(ExtraKey.EXTRA_JUMPFROM_WHERE_TYPE);
            extra_carattestation = extras_bundle.getParcelable(ExtraKey.EXTRA_CARATTESTATION);

            if (extra_carattestation != null) {
                carAttestationId_upLoad = extra_carattestation.getCarAttestationId();
            }

        }

    }
}